<template>
  <div class="building">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-row>
        <el-col :span="2.5">
          <el-form-item prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="房间状态"
                clearable
                style="width: 120px"
                @change="handleQuery"
            >
                <el-option
                  v-for="dict in sys_room_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
            </el-select>
            <el-popover
              placement="bottom"
              :width="200"
              trigger="click"
            >
              <template #reference>
                <el-icon class="ml10" style="color: var(--el-text-color-placeholder);"><QuestionFilled /></el-icon>
              </template>
              <div>
                <div>空房：无入住人的房间</div>
                <div>账单欠费：有账单到期未支付或剩余水电欠费</div>
                <div>逾期：有逾期未退房的房间</div>
                <div>维修：有报修的房间</div>
                <div>即将到期：即将到期的房间</div>
                <div>水电欠费：入住中水电欠费</div>
              </div>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="2.5">
           <el-form-item label="时间筛选" style="width: 308px" v-if="queryParams.status === '1'">
            <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="2.5">
          <el-form-item prop="searchStr">
            <el-input
              v-model="queryParams.searchStr"
              placeholder="请输入入住人或房源地址"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            >
              <template #append>
                <el-button :icon="Search" @click="handleQuery" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2.5">
          <el-form-item>
            <div>数量：<span style="font-size: 20px;font-style: italic;">{{ roomCount }}</span> 间</div>
          </el-form-item>
        </el-col>
        <div style="margin-left: auto;">
          <el-button plain type="primary" @click="() => entireBuildingVisible = true">+ 添加整栋</el-button>
          <el-button type="primary" @click="() => floorVisible = true">+ 添加整层</el-button>
        </div>
      </el-row>
    </el-form>
    <el-radio-group v-model="apartment" @change="handleRadio">
      <el-radio-button label="" >全部</el-radio-button>
      <el-radio-button :label="item.buildingId" v-for="item in buildingList" :key="item.buildingId">{{ item.name }}</el-radio-button>
    </el-radio-group>
    <template v-if="apartment !== ''">
      <FloorLine
        :buildingId="apartment"
        :option="floorLineOption"
        class="mt20"
        @line-change="handleFloorLineChange"
        @edit="handleFloorLineEdit"
        @delete="handleFloorLineDel" />
    </template>
    <!-- <el-button @click="load">下一页</el-button> -->
    <div v-if="floorList.length > 0" class="mt20"  v-infinite-scroll="load" infinite-scroll-delay="600" :infinite-scroll-immediate="false" style="overflow: auto;height: 600px;">
        <RoomFloor
          v-for="floor in floorList"
          :key="floor.floorId"
          :name="floor.buildingName"
          :floorName="floor.floorName"
          :floorId="floor.floorId"
          :roomList="floor.roomList"
          :info="floor"
          @addRoom="handleAddRoom"
          @refresh="handleQuery"
        />
      <div v-loading="loading" style="height: 50px"></div>
    </div>
    <el-empty v-else description="暂无房间信息" />
    <AddEntireBuilding
      v-model:value="entireBuildingVisible"
      @ok="handleEntireBuildingOk"
      @cancel="() => entireBuildingVisible = false" />
    <AddFloor
      v-model:value="floorVisible"
      :buildingList="buildingList"
      @ok="hangdleFloorOk"
      @cancel="() => floorVisible = false"
    />
  </div>
</template>
<script setup name="Building">
import { QuestionFilled, Search, MoreFilled } from '@element-plus/icons-vue'
import RoomFloor from './component/roomFloor.vue'
import AddEntireBuilding from './component/addEntireBuilding.vue'
import AddFloor from './component/addFloor.vue'
import FloorLine from './component/floorLine.vue'
import buildApi from '@/api/room/building.js'
import roomApi from '@/api/room/room'
import useUserStore from '@/store/modules/user'
import { buildTimeList } from 'element-plus'
import { computed, reactive, watch } from 'vue'
import { useAsyncQueue } from '@vueuse/core'

const { proxy } = getCurrentInstance()
// 系统字典的获取方式
const { sys_room_status } = proxy.useDict("sys_room_status");


const dateRange = ref([]);
const showSearch = ref(true)
const roomCount = ref(0)
const apartment = ref('')
const entireBuildingVisible = ref(false)
const floorVisible = ref(false)
const floorList = ref([])
const buildingId = ref(null)
const buildingList = ref([])
const floorIds = ref([])
const floorLineOption = ref([])
const finish = ref(false)
const roomTotal = ref(0)
const queue = ref([])
const loading = ref(true)
const activeStatus = ref('')

function handleRadio(value) {
  if (value === '') {
    floorIds.value = []
    floorLineOption.value = []
    buildingId.value = null
  } else {
    buildingId.value = value
    let findIndex = buildingList.value.findIndex(item => item.buildingId === value)
    floorIds.value = []
    floorLineOption.value = findIndex !== -1 ? 
      buildingList.value[findIndex].floorList
      .map(item => {
        console.log(item);
        floorIds.value.push(item.floorId)
        return { label: `${item.floorName} 层`, value: item.floorId }
      }) : []
  }
  finish.value = false
  roomTotal.value = 0
  queryParams.value.pageNum = 1
  floorList.value = []
  getRoomList()
}
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 40,
    status: undefined,
    searchStr: undefined
  },
})
const { queryParams } = toRefs(data);

function getList() {
  console.log('queryParams>>>', proxy.addDateRange(queryParams.value, dateRange.value));
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  floorList.value = []
  finish.value = false
  getRoomList();
};
// 添加整栋确认事件
function handleEntireBuildingOk(value) {
  const params = Object.assign(value, { apartmentId: useUserStore().apartment.apartmentId })
  buildApi.addBuilding(params).then(res => {
    finish.value = false
    getBuildingList()
    getRoomList()
    entireBuildingVisible.value = false
  })
}

// 添加整层确认事件
function hangdleFloorOk(floor) {
  const params = {
    apartmentId: useUserStore().apartment.apartmentId,
    buildingId: floor.buildingId,
    floors: [{
      floor: floor.floor,
      roomNameList: floor.chamberNameList.split(',')
    }]
  }
  buildApi.addBuilding(params).then(res => {
    getRoomList()
    floorVisible.value = false
  })
}

// 楼层选择变化事件
function handleFloorLineChange(value) {
  floorIds.value = value
  floorList.value = []
  queryParams.value.pageNum = 1
  finish.value = false
  getRoomList()
}

// 添加房间成功
function handleAddRoom() {
  getBuildingList()
  floorList.value = []
  queryParams.value.pageNum = 1
  finish.value = false
  getRoomList()
}

// 修改楼层名称
function handleFloorLineEdit() {
  getBuildingList()
  floorList.value = []
  queryParams.value.pageNum = 1
  finish.value = false
  getRoomList()
}
// 删除楼栋
function handleFloorLineDel() {
  finish.value = false
  getBuildingList()
  getRoomList()
}

// 分页加载
const load = async () => {
  if (finish.value) return false;
  queryParams.value.pageNum++
  getRoomList()
}

function getBuildingList() {
  buildApi.getList().then(res => {
    console.log(res)
    buildingList.value = res
  })
}

function getRoomList() {
  const params = {
    pageSize: queryParams.value.pageSize,
    pageNum: queryParams.value.pageNum,
    type: 1,
    floorIds: floorIds.value,
    buildingId: buildingId.value,
    name: queryParams.value.searchStr
  }
  if (queryParams.value.status && queryParams.value.status !== '0') {
    params.status = queryParams.value.status
  }
  loading.value = true
  roomApi.getList(params).then(res => {
    let lastItem = {}
    loading.value = false
    res.rows.forEach((items, index) => {
      items.floorList.forEach((item, ind) => {
        let value = {
          label: `${items.buildingName} · ${item.floorName}层`,
          buildingName: items.buildingName,
          buildingId: items.buildingId,
          floorId: item.floorId,
          floorName: item.floorName,
          roomList: item.roomList
        }
        
        if (params.pageNum > 1 && index === 0 && ind === 0) {
          lastItem = floorList.value[floorList.value.length - 1]
          if (lastItem && lastItem.buildingName === items.buildingName && lastItem.floorName === item.floorName) {
            lastItem = floorList.value.pop()
            roomTotal.value += item.roomList.length
            item.roomList.forEach(room => {
              lastItem.roomList.push(room)
            })
            value.roomList = lastItem.roomList
          }
        }

        roomTotal.value += item.roomList.length
        floorList.value.push(value)
      })
    })
    if (roomTotal.value >= res.total) finish.value = true
    roomCount.value = res.total
  })
  
}
getBuildingList()
getRoomList()
// queryParams.value.pageNum++
// getRoomList()

function handleStatusTabChange(tab) {
  queryParams.value.status = tab.props.name
  handleQuery()
}

function resetQuery() {
  queryRef.value?.resetFields()
  activeStatus.value = ''
  handleQuery()
}

watch(() => queryParams.value.status, (val) => {
  activeStatus.value = val || ''
})

watch(() => activeStatus.value, (val) => {
  queryParams.value.status = val
})
</script>